import json
import os
import uuid
from hashlib import md5
from src.custom.tools import write_json, read_json


class UserInfo:

    def __init__(self, name: str, dir_work: str = '.'):
        self.name = name                # 不能改
        self.session_name = None        # name: str
        # TODO 当没有保存聊天历史记录的时候，应该去除掉元素
        self.session_list = []          # {name: id} 名可以变，且唯一，id是保存路径不能变
        self.dir_work = os.path.join(dir_work, "userinfo", self.name + '.json')

    def save(self) -> bool:
        return write_json(self.dir_work, self.__dict__)

    def load(self) -> bool:
        """加载用户信息，新用户返回False，已存在成功加载返回True"""
        flag = read_json(self.dir_work)
        if flag:
            self.__dict__.update(flag)
            return True
        return False

    def change_session(self, session_name: str) -> bool:
        """从一个会话切换到另一个已有的会话中去"""
        if session_name is None: return False
        if session_name in self.session_list:
            self.session_name = session_name
            return True
        return False

    def set_session_name(self, session_name: str) -> bool:
        """更改当前会话的会话名，会话名唯一不可重复"""
        if session_name is None:
            return False
        if session_name in self.session_list:
            return False
        if self.session_name is not None:
            self.session_list.remove(self.session_name)
        self.session_name = session_name
        self.session_list.append(session_name)
        return True

    def new_session(self, session_name: str) -> bool:
        """新建一个会话"""
        if session_name is None: return False
        if session_name in self.session_list:
            return False
        # 新建不更改，通过change更改
        self.session_list.append(session_name)
        return True

    def add_session_to_list(self, session_name: str) -> bool:
        """逻辑和new_session相同，为了使用列表，来排除相同名的情况，使用new也可以，只不过在函数的语义上就不好理解了"""
        if session_name is None: return False
        if session_name in self.session_list:
            return False
        # 新建不更改，通过change更改
        self.session_list.append(session_name)
        return True

if __name__ == "__main__":
    os.rename('./storage/aa.txt', './storage/bb.txt')